'use client';

import { useState } from 'react';
import { Button } from '@heroui/button';
import { Input } from '@heroui/input';
import { Card, CardBody, CardHeader } from '@heroui/card';
import { Spinner } from '@heroui/spinner';
import { 
  useVideoList, 
  useVideoSearch, 
  usePopularVideos,
  useFileUpload 
} from '@/hooks/useApi';
import { api } from '@/lib/api';

export const ApiUsageExample = () => {
  const [searchKeyword, setSearchKeyword] = useState('');

  // 使用视频列表Hook
  const { 
    videos, 
    loading: videosLoading, 
    error: videosError, 
    loadMore, 
    refresh 
  } = useVideoList({ pageSize: 10 });

  // 使用搜索Hook
  const { 
    results: searchResults, 
    loading: searchLoading, 
    search 
  } = useVideoSearch();

  // 使用热门视频Hook
  const { 
    data: popularVideos, 
    loading: popularLoading 
  } = usePopularVideos(5);

  // 使用文件上传Hook
  const { uploading, upload } = useFileUpload();

  // 处理搜索
  const handleSearch = () => {
    if (searchKeyword.trim()) {
      search(searchKeyword);
    }
  };

  // 处理文件上传
  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      try {
        await upload(file, 'video');
        alert('上传成功！');
      } catch (error) {
        alert('上传失败！');
      }
    }
  };

  // 直接调用API示例
  const handleDirectApiCall = async () => {
    try {
      const stats = await api.getStats();
      alert(`统计信息: ${JSON.stringify(stats)}`);
    } catch (error) {
      alert('获取统计信息失败！');
    }
  };

  return (
    <div className="space-y-6 p-6">
      <h1 className="text-2xl font-bold">API使用示例</h1>

      {/* 搜索示例 */}
      <Card>
        <CardHeader>
          <h2 className="text-lg font-semibold">视频搜索</h2>
        </CardHeader>
        <CardBody>
          <div className="flex gap-2 mb-4">
            <Input
              placeholder="输入搜索关键词"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
            />
            <Button 
              onClick={handleSearch}
              isLoading={searchLoading}
            >
              搜索
            </Button>
          </div>
          
          {searchResults.length > 0 && (
            <div className="space-y-2">
              <h3 className="font-medium">搜索结果:</h3>
              {searchResults.map((video) => (
                <div key={video.id} className="p-2 border rounded">
                  <p className="font-medium">{video.title}</p>
                  <p className="text-sm text-gray-600">{video.uploader}</p>
                </div>
              ))}
            </div>
          )}
        </CardBody>
      </Card>

      {/* 热门视频示例 */}
      <Card>
        <CardHeader>
          <h2 className="text-lg font-semibold">热门视频</h2>
        </CardHeader>
        <CardBody>
          {popularLoading ? (
            <Spinner />
          ) : (
            <div className="space-y-2">
              {popularVideos?.map((video) => (
                <div key={video.id} className="p-2 border rounded">
                  <p className="font-medium">{video.title}</p>
                  <p className="text-sm text-gray-600">{video.views} 观看</p>
                </div>
              ))}
            </div>
          )}
        </CardBody>
      </Card>

      {/* 视频列表示例 */}
      <Card>
        <CardHeader>
          <div className="flex justify-between items-center">
            <h2 className="text-lg font-semibold">视频列表</h2>
            <div className="space-x-2">
              <Button size="sm" onClick={refresh}>
                刷新
              </Button>
              <Button size="sm" onClick={loadMore}>
                加载更多
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardBody>
          {videosError && (
            <div className="text-red-500 mb-4">
              错误: {videosError.message}
            </div>
          )}
          
          {videosLoading ? (
            <Spinner />
          ) : (
            <div className="space-y-2">
              {videos.map((video) => (
                <div key={video.id} className="p-2 border rounded">
                  <p className="font-medium">{video.title}</p>
                  <p className="text-sm text-gray-600">
                    {video.uploader} • {video.views} 观看 • {video.uploadTime}
                  </p>
                </div>
              ))}
            </div>
          )}
        </CardBody>
      </Card>

      {/* 文件上传示例 */}
      <Card>
        <CardHeader>
          <h2 className="text-lg font-semibold">文件上传</h2>
        </CardHeader>
        <CardBody>
          <input
            type="file"
            accept="video/*"
            onChange={handleFileUpload}
            disabled={uploading}
            className="mb-2"
          />
          {uploading && <Spinner />}
        </CardBody>
      </Card>

      {/* 直接API调用示例 */}
      <Card>
        <CardHeader>
          <h2 className="text-lg font-semibold">直接API调用</h2>
        </CardHeader>
        <CardBody>
          <Button onClick={handleDirectApiCall}>
            获取统计信息
          </Button>
        </CardBody>
      </Card>
    </div>
  );
};
